package com.bootdo.fx.controller;


import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.utils.*;
import com.bootdo.fx.domain.OrderInfoDO;
import com.bootdo.fx.domain.UserInfoDO;
import com.bootdo.fx.service.OrderInfoService;
import com.bootdo.fx.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/wx")
public class WXController {

    @Autowired
    private  UserInfoService userInfoService;

    @Autowired
    private BootdoConfig bootdoConfig;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private IdWorker idWorker;

    @GetMapping("/index")
    void index(HttpServletResponse response,HttpServletRequest request) throws IOException {

        String url = request.getRequestURL().toString();
        String[] s = url.split("/wx/");
        response.sendRedirect(s[0] + "/dist/saleIndex.html");
    }

    @RequestMapping("/testLogin")
    @ResponseBody
    public String testLogin(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        UserInfoDO userInfoDO = userInfoService.get(1L);
        request.getSession().setAttribute("userInfo", userInfoDO);
        return "test账号登录成功！！！";
    }


    @RequestMapping("/weixinAutoLogin")
    public void weixinAutoLogin(String userId,HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /**
         *这儿一定要注意！！首尾不能有多的空格（因为直接复制往往会多出空格），其次就是参数的顺序不能变动
         **/
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AuthUtil.APPID +
                "&redirect_uri=" + URLEncoder.encode(AuthUtil.Notify_url, "UTF-8") +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=" + userId +
                "#wechat_redirect";
        response.sendRedirect(url);
    }

    @RequestMapping("/weixinComeback")
    public void weixinComeback(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");

        String code = request.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID +
                "&secret=" + AuthUtil.APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("access_token");
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        //System.out.println(userInfo);

        UserInfoDO ui = new UserInfoDO();
        ui.setUserId(idWorker.nextId());
        ui.setUserAvatar(String.valueOf(userInfo.get("headimgurl")));

        //用户的上级分销用户ID
        String upUserId = request.getParameter("state");
        if(upUserId != null && upUserId.length() > 0 && !upUserId.equals("null")) {
            ui.setUpUserId(Long.parseLong(upUserId));
        }else{
            ui.setUpUserId(0L);
        }
        ui.setUserCity(String.valueOf(userInfo.get("city")));
        ui.setUserCountry(String.valueOf(userInfo.get("country")));
        ui.setUserCreateTime(new Date());
        ui.setUserIsDistributor(0);
        ui.setUserNickname(String.valueOf(userInfo.get("nickname")));
        ui.setUserName(String.valueOf(userInfo.get("nickname")));
        ui.setUserOpenid(openid);
        if(userInfo.get("sex") != null) {
            ui.setUserSex(Integer.parseInt(String.valueOf(userInfo.get("sex"))));
        }
        ui.setUserProvince(String.valueOf(userInfo.get("province")));


        Map<String, Object> map = new HashMap<>();
        map.put("userOpenid", openid);
        List<UserInfoDO> userIn = userInfoService.list(map);
        UserInfoDO userInfo1 = null;
        for (UserInfoDO u : userIn) {
            userInfo1 = u;
        }
        int b = 0;
        if (userInfo1 == null) {
            b = userInfoService.saveUserAndFundsInfo(ui);
        } else {
            ui = userInfo1;
        }

        //用户信息存放到session里面
        //request.getSession().setAttribute("userInfo", ui);

        String uu = request.getRequestURL().toString();
        String[] s = uu.split("/wx/");
        response.sendRedirect(s[0] + "/dist/index.html?userId=" + ui.getUserId());

    }


    /*
    * 支付订单
    * @param orderId 订单id，totalFee 订单金额
    * */
    @RequestMapping("/payOrder")
    @ResponseBody
    public void payOrder(String orderId, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        OrderInfoDO order = orderInfoService.get(Long.parseLong(orderId));
        Map<String, String> map = WeiChartUtil.getPreyId(orderId, String.valueOf(order.getOrderAmount()));
        // 预付商品id
        String prepay_id = "";
        String return_code = map.get("return_code");
        String result_code = map.get("result_code");
        if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
            prepay_id = map.get("prepay_id");
        }

        Map<String, String> payMap = new HashMap<String, String>();
        payMap.put("appId", AuthUtil.APPID);
        payMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
        payMap.put("nonceStr", WeiChartUtil.getRandomString());
        payMap.put("signType", "MD5");
        payMap.put("package", "prepay_id=" + prepay_id);
        String paySign = WeiChartUtil.getSign(payMap);
        payMap.put("paySign", paySign);
        WebUtil.response(response, payMap);
    }


    @RequestMapping("/wxPayReturn")
    @ResponseBody
    public void wxPayReturn(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String return_code = request.getParameter("return_code");//返回状态吗
        String out_trade_no = request.getParameter("out_trade_no");//商户订单号
        String WEXIN_OPENID = request.getParameter("openid");//微信openid
        String transaction_id = request.getParameter("transaction_id");//微信支付单号
        if ("SUCCESS".equals(return_code)) {
            OrderInfoDO order = orderInfoService.get(Long.parseLong(out_trade_no));
            order.setOrderPayType(0);
            order.setOrderPayStatus(1);
            order.setOrderStatus(1);
            orderInfoService.update(order);
            response.getWriter().write("yes!!");
        }else{
            response.getWriter().write("fail!!");
        }
    }


    @RequestMapping("/indexPage")
    public String indexPage() {
        return "index";
    }


    @RequestMapping("/getQrImg")
    @ResponseBody
    public JsonResult getQrImg(String userId,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        String fileUrl = "";
        if(userId == null && userId.length() == 0){
            return ResultUtil.renderSuccess();
        }
        UserInfoDO userInfoDO = userInfoService.get(Long.parseLong(userId));
        if(userInfoDO != null) {
            Long i = Long.parseLong(userId);
            if(i > 0 && userInfoDO.getQrcode() == null) {
                fileUrl = "/files/" + QrcodeUtil.generateQrcode(userId,bootdoConfig.getUploadPath());
            }
        }
        if(fileUrl.length() > 0){
            userInfoDO.setQrcode(fileUrl);
            int num = userInfoService.update(userInfoDO);
            if(num > 0){
                return ResultUtil.renderSuccess(userInfoDO);
            }else{
                return ResultUtil.renderError();
            }
        }else{
            return ResultUtil.renderSuccess(userInfoDO);
        }

    }


    @RequestMapping("/saveUserSession")
    @ResponseBody
    public JsonResult saveUserSession(String str,HttpServletRequest re,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        //HttpServletRequest re = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        int max = re.getSession().getMaxInactiveInterval();
        if(str == null || str.length() == 0){
            return ResultUtil.renderError();
        }
        String st = str.split("#")[0];
        String s = st.substring(1,st.length());
        Long id = Long.parseLong(s);
        UserInfoDO userInfoDO = userInfoService.get(id);
        if(userInfoDO != null){
            re.getSession().setAttribute("userInfo",userInfoDO);

            UserInfoDO obj = (UserInfoDO) re.getSession().getAttribute("userInfo");
            return ResultUtil.renderSuccess();
        }else{
            return ResultUtil.renderError();
        }
    }



}
